package sunyu.kit.database;

import org.nutz.dao.ConnCallback;
import org.nutz.dao.impl.DaoRunner;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * 让nutzDao使用spring事物配置
 *
 * @author 孙宇
 */
public class SpringDaoRunner implements DaoRunner {

    @Override
    public void run(DataSource dataSource,
                    ConnCallback callback) {
        Connection conn = DataSourceUtils.getConnection(dataSource);
        try {
            callback.invoke(conn);
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new RuntimeException(e);
            }
        } finally {
            DataSourceUtils.releaseConnection(conn, dataSource);
        }
    }
}
